/**
 * @FileName: autoSelectTree.js 
 * @Summary: 树的下拉选择框
 * @Encoding: UTF-8 
 * @Author jcc
 * @Version: 1.0 
 * @Date: 2010-01-12
 **/

/**
 * 关闭层
 * @param {} displayDiv
 */
function closeDiv(displayDiv){	
	$(displayDiv).css("left","-9999px");
	$(displayDiv).css("top","-9999px");
} ;

(function($) {
$.fn.autoSelectTree = function(config) {
	return this.each(function(){
		$(this).attr("autocomplete", "off");
		config.currentDom = this;
		
		config.ajaxDivId = "autoSelectDiv"+this.id;
		config.width = config.width||350;
		config.searchKeyCode = config.searchKeyCode || 13;//默认回车查询
		config.index=-1;
				
		config.ajaxPara = {
		};
		 
		config.query = true;			//默认按回车查询 add by liaoqs
		config.isAjaxDivHide = true;	//标识div层是否隐藏  gxl 20090826
		config.thisId = this.id;
		
		$(this).keydown(function(e){
			var kc = getKeyCode(e);
			if(kc==40){
				//1.支持下箭头事件
				var treeNodeSize = $("#"+config.ajaxDivId+" [class*='x-tree-node-el']:visible").size();
				if(config.index == treeNodeSize-1 ){
					config.index=0;
				}else
					config.index++;
					
				setArrowMove(config) ;
				
				
			}else if(kc==38){
				//2.支持上箭头事件,进行回调
				var treeNodeSize = $("#"+config.ajaxDivId+" [class*='x-tree-node-el']:visible").size();
				//alert("treeNodeSize:"+treeNodeSize+",config.index:"+config.index)
				if(config.index<=0)
					config.index=treeNodeSize-1;
				else
					config.index--;	

				setArrowMove(config) ;
				
			}
			else if(kc==39){
				//右键头展开
				var domObj = getCurrentSelectedArr(config).get(0) ;
				if(domObj){
					var node = eval(config.treeName).getNodeById(domObj.getAttribute("ext:tree-node-id")) ;
					node.expand() ;
				}
				//setArrowMove(config) ;		
			}else if(kc==37){
				//左箭头收缩
				var domObj = getCurrentSelectedArr(config).get(0) ;
				if(domObj){
					var node = eval(config.treeName).getNodeById(domObj.getAttribute("ext:tree-node-id")) ;
					node.collapse() ;
				}	
			}/**/
			else if(kc==9){
				return;
			}else if(kc==config.searchKeyCode || kc ==13){
				//3.回车选择
				//增加按回车键后选择文本，add by liuzg.
				if(!config.query && kc == 13 || (config.searchKeyCode !=13 && kc == 13) )
				{ 
					
					if(config.index!=-1){
						var domObj = getCurrentSelectedArr(config).get(0) ;
						if(domObj){
							var node = eval(config.treeName).getNodeById(domObj.getAttribute("ext:tree-node-id")) ;
							eval(config.callback)(node) ;
							closeDiv($("#" + config.ajaxDivId));
						}
						else{
							$(this).val("");
							closeDiv($("#" + config.ajaxDivId));
						}
						
						config.index = -1;					
					}else{
						$(this).val("");					
					}
					config.query = true;
					IS_FROM_SELECT[this.id] = true;			// gxl 20090826
					config.isAjaxDivHide = true;	// gxl 20090826
				}else{				
					getSelectHtml(config);
					return false;
				}			
			}else{
				if(config.characterNum && config.currentDom.value.length>=config.characterNum)
					getSelectHtml(config);
				if(config.currentDom.value==''){
					closeDiv($("#" + config.ajaxDivId));
				}
				config.query = true;
			}
		});
				
	});
};

/**
 * 获取前一个选中
 */
function getPrevSelectedArr(config){
	return  $("#"+config.ajaxDivId+" [wef-selected='1']") ;
}

/**
 * 获取当前选中
 */
function getCurrentSelectedArr(config){
	return  $("#"+config.ajaxDivId+" [class*='x-tree-node-el']:visible:eq("+config.index+")") ;
}

/**
 * 设置上箭头与下箭头的选中
 */
function setArrowMove(config){
	var prevSelectedArr = getPrevSelectedArr(config) ;
	
	if(prevSelectedArr.size()!=0){
		$.each(prevSelectedArr ,function() {			
			this.style.backgroundColor='' ;
			this.setAttribute("wef-selected" , 0 ) ;
		}) ;
		
	}
	var currentSelectedObj = getCurrentSelectedArr(config).get(0) ;
	if(currentSelectedObj){
		currentSelectedObj.setAttribute("wef-selected" , "1") ;
		
		currentSelectedObj.style.backgroundColor = config.selectRowBgcolor || ProjConfigParam.SELECT_ROW_BGCOLOR ;
	}
}

/**
 * 缓存时,重置index
 */
function resetCls(config){
	config.index = -1 ;
	
	var oldObjArr = $("#"+config.ajaxDivId+" [class*='" + config.uniqueBgCss + "']") ;
	if(oldObjArr.size()!=0){
		var oldObj = oldObjArr.get(0) ;
		var oldClassName = oldObj.className ;
		var newClassName = oldClassName.substring(0,oldClassName.length - (config.uniqueBgCss.length+1)) ; 
//		oldObjArr.attr("class" , newClassName) ;
		$.each(oldObjArr ,function() {
			this.className = newClassName ;
		}) ;
		
	}	
}

/**
 * ajax请求，从后台获取需要的数据
 */
function getSelectHtml(config){
	config.ajaxPara.selectId = config.currentDom.id;
	config.ajaxPara.fieldValue = config.currentDom.value;
	config.ajaxPara.callback = config.callback ;
	config.ajaxPara.ajaxDivId = config.ajaxDivId ;
	config.ajaxPara.autoFilter = config.autoFilter ;
	config.ajaxPara.autoExpand = config.autoExpand ;
	config.ajaxPara.cachable = config.cachable ;
	config.ajaxPara.selectCondition = config.selectCondition; //选择节点时加条件判断
	config.ajaxPara.errorHint = config.errorHint;
	
	
	startLoading(config);
	var currentUrl = config.url ;

	
	$.ajax({
		type : "POST",
		url : currentUrl,
		contentType : "application/x-www-form-urlencoded;charset=UTF-8",
		timeout : 20000,
		error : function() {
			alert('连接失败！');//$("#" + config.ajaxDivId).hide();
		},
		data : config.ajaxPara,
		success : function(msg) {
			openDiv(config,msg,currentUrl);
			closeLoading(config);
		}
	});

};

/**
 * 打开下拉框内容
 */
function openDiv(config,msg,url) {
	 
	var obj = config.currentDom;
	var divId = config.ajaxDivId;
	var width = config.width;
	var opDiv = document.getElementById(divId);
	var offset = $(obj).offset();
	if (!opDiv) {
		opDiv = document.createElement('div'); // 创建层
		opDiv.id = divId;
		document.body.appendChild(opDiv);
	}
	$("#" + config.ajaxDivId).html(msg);
	//$("#" + config.ajaxDivId).attr("config", config) ;
	//$("#" + config.ajaxDivId).attr("config" , config) ;
	$("#" + config.ajaxDivId).get(0).config = config ;
	var w = document.body.offsetWidth - offset.left;
	var left = null;
	if (w < width) {
		left = offset.left + obj.offsetWidth - width + 7;
	} else {
		left = offset.left;
	}
	var bottomDistance=document.body.clientHeight-offset.top;
	var topDistance=offset.top-obj.offsetHeight;
	var gridObj=document.getElementById(config.ajaxDivId);
	var top = offset.top + $(obj).height() + 3;
	if(gridObj.offsetHeight+5>bottomDistance && topDistance>gridObj.offsetHeight)
		top=offset.top-gridObj.offsetHeight-3;
	$(opDiv).css("left",left+"px");
	$(opDiv).css("top",top+"px");
	$(opDiv).css("width",width+"px");
	opDiv.style.zIndex = '9999';
	opDiv.style.position = 'absolute';
	opDiv.style.cursor = 'default';
	//$(opDiv).slideDown(150);
	document.onclick = function(e) {
		$("#"+config.currentDom.id+"gotoPageInput").val("");
		OnDocClick(e, $(obj), $(opDiv),config);
		config.isAjaxDivHide = true;	// gxl 20090826
	};
	//alert("opendiv:" + divId);
	//alert("opendiv+config:" + $("#" + divId).attr("config").query);
	config.query=false;
	//alert("opendiv+config:" + $("#" + divId).attr("config").query);//config.ajaxDivId
}

function startLoading(config){
	var obj = config.currentDom;
	var offset = $(obj).offset();
	var top = offset.top + $(obj).height() + 5;
	var left = offset.left;
	var loadingDiv=document.getElementById(config.currentDom.id+'LoadingDiv');
	if(!loadingDiv){
		loadingDiv=document.createElement('div');
		loadingDiv.id=config.currentDom.id+'LoadingDiv';
		document.body.appendChild(loadingDiv);
	}
	$(loadingDiv).html("<img src='"+App.ctx+"/images/icon/loading.gif'></img>Loading...");
	$(loadingDiv).css("left",left+"px");
	$(loadingDiv).css("top",top+"px");
	loadingDiv.style.zIndex = '9999';
	loadingDiv.style.position = 'absolute';
}

function closeLoading(config){
	var loadingDiv=document.getElementById(config.currentDom.id+'LoadingDiv');
	if(loadingDiv){
		$(loadingDiv).css("left","-9999px");
		$(loadingDiv).css("top","-9999px");
	}
}


/**
 * 给整个页面添加点击事件 用于用户点击下拉框外的区域时隐藏下拉框
 */
function OnDocClick(e,inputDiv,displayDiv,config){
	var x, y, t, b, l, r;
		var d;
		if (window.event) {
			e = window.event;
			x = e.clientX + document.body.scrollLeft - document.body.clientLeft;
			y = e.clientY + document.body.scrollTop - document.body.clientTop;
		} else {
			x = e.pageX;
			y = e.pageY;
		}
		t = inputDiv.offset().top;
		l = inputDiv.offset().left;
		b = t + inputDiv.height();
		r = l + inputDiv.width();
		if (x >= l && x < r && y >= t && y < b) {
			return;
		}
		t = displayDiv.offset().top;
		l = displayDiv.offset().left;
		b = t + displayDiv.height();
		r = l + displayDiv.width();
		if (x >= l && x < r && y >= t && y < b) {
			return;
		}
		//$(displayDiv).slideUp(350);
		closeDiv(displayDiv);//隐藏div
		config.query = true;
		document.onclick = null;
}

function getKeyCode(e){
	var msie = (document.all) ? true : false; 
  	var keyCode; 
    if(!msie)
        keyCode=e.which; 
    else
        keyCode=event.keyCode; 
    return keyCode;
}
})(jQuery) ;



	